<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="完结任务"
    width="600"
    class="dialogStyle"
    @close="handleClose"
  >
    <el-form
      :model="formParams"
      label-width="120px"
      ref="ruleFormRef"
      :rules="rulesForm"
    >
      <el-form-item label="实际开始时间:" prop="realStartTime">
        <el-date-picker
          v-model="formParams.realStartTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="实际完成时间:" prop="realEndTime">
        <el-date-picker
          v-model="formParams.realEndTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="实际工时：" prop="workHour">
        <el-input v-model="formParams.workHour" placeholder="请输入实际工时">
          <template #append>小时</template></el-input
        >
      </el-form-item>
      <!-- 
        显示条件：
          测试问题
          负责人、处理人不为空
          登录人为负责人
          处理人员不包括负责人
       -->
      <el-form-item
        label="通过情况:"
        prop="passFlag"
        v-if="
          (dialogParam.businessType === '11' ||
            dialogParam.businessType === '12') &&
          dialogParam.directorId &&
          dialogParam.playersId &&
          userStore.userInfo.userId == dialogParam.directorId &&
          !dialogParam.playersId.includes(userStore.userInfo.userId)
        "
      >
        <el-radio-group v-model="formParams.passFlag">
          <el-radio :label="1">通过</el-radio>
          <el-radio :label="0">不通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="完成情况说明:" prop="remark">
        <el-input
          v-model="formParams.remark"
          type="textarea"
          maxlength="300"
          placeholder="请输入完成情况说明"
          :rows="4"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="上传附件：">
        <el-upload
          v-model:file-list="formParams.fileList"
          class="upload-demo"
          action="#"
          :before-upload="beforeAvatarUpload"
          :http-request="handleFileChange"
          accept=".rar, .zip, .doc, .docx, .pdf"
          :show-file-list="false"
        >
          <el-button type="default" style="font-size: 14px"
            ><el-icon><UploadFilled /></el-icon>上传文件</el-button
          >
          <template #tip>
            <div class="el-upload__tip float-right">
              支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过{{
                dialogParam.tableName == 'ord_project.materials'
                  ? '100MB'
                  : '20MB'
              }}且只能上传一份文件
            </div>
          </template>
        </el-upload>
        <div class="text-14px mt-10px" style="width: 100%">
          <div v-for="(item, index) in fileList" :key="item.fileId">
            <a :href="item.url" target="_blank" class="text-#409eff">{{
              item.origFileName
            }}</a>
            <el-button text plain @click="delFileName(index)">删除</el-button>
          </div>
        </div>
      </el-form-item>

      <div class="footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="btnLoading"
          >保存</el-button
        >
      </div>
    </el-form>
  </el-dialog>
</template>
<script setup name="AppendTask">
import { reactive, getCurrentInstance, watchEffect } from 'vue'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { getTaskDeal } from '@/api/taskManage/task'
import { addManage } from '@/api/system/notice'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { getTodoMessageHandle } from '@/api/businessSettings/agent'
const { proxy } = getCurrentInstance()
// 通用数据store
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const props = defineProps({
  // 弹出框是否显示
  dialogParam: {
    required: true
  },
  rowId: {
    type: String || Number
  }
})
const data = reactive({
  dialogVisible: false,
  gettime: '',
  formParams: {},
  // 表单校验
  rulesForm: {
    remark: [
      { required: true, message: '完成情况说明不能为空', trigger: 'blur' }
    ],
    realStartTime: [
      { required: true, message: '开始时间不能为空', trigger: 'blur' }
    ],
    realEndTime: [
      { required: true, message: '结束时间不能为空', trigger: 'blur' }
    ],

    workHour: [
      { required: true, message: '实际工时不能为空', trigger: 'blur' },
      {
        pattern: /^(([+-])?([0-9]+(\.[0-9]{1,2})?))$/,
        message: '输入数字及小数点,且只能有两位小数点'
      }
    ],
    passFlag: [{ required: true, message: '通过情况不能为空', trigger: 'blur' }]
  }
})
const { dialogVisible, formParams, rulesForm, gettime } = toRefs(data)
const btnLoading = ref(false) //按钮加载状态

watch(
  () => props.dialogParam,
  val => {
    if (JSON.stringify(props.dialogParam) != '{}') {
      init()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
//获取当前时间
function getTime() {
  var _this = this
  let yy = new Date().getFullYear()
  var mm =
    new Date().getMonth() > 9
      ? new Date().getMonth() + 1
      : new Date().getMonth() == 9
      ? new Date().getMonth() + 1
      : '0' + (new Date().getMonth() + 1)
  var dd =
    new Date().getDate() < 10
      ? '0' + new Date().getDate()
      : new Date().getDate()
  let hh = new Date().getHours()
  let mf =
    new Date().getMinutes() < 10
      ? '0' + new Date().getMinutes()
      : new Date().getMinutes()
  let ss =
    new Date().getSeconds() < 10
      ? '0' + new Date().getSeconds()
      : new Date().getSeconds()
  gettime.value = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
  console.log('gettime', gettime.value)
}
async function init() {
  dialogVisible.value = props.dialogParam.isVisible
  getTime()
}
/*** 文件上传 start */
let fileList = ref([])
/**文件上传 限制条件**/
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}
//删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/***任务完结***/
const handleSubmit = async () => {
  proxy.$refs['ruleFormRef'].validate(async valid => {
    if (valid) {
      let params = {}
      params.dealFileName = []
      params.dealFilePath = []
      params.remark = formParams.value.remark
      params.id = props.dialogParam.operateId
      params.taskId = props.dialogParam.taskId
      params.dealStatus = 8 //结果饭溃
      params.realStartTime = formParams.value.realStartTime
      params.realEndTime = formParams.value.realEndTime
      params.workHour = formParams.value.workHour
      params.passFlag = formParams.value.passFlag

      //上传的文件
      for (let i = 0; i < fileList.value.length; i++) {
        params.dealFileName.push(fileList.value[i].origFileName)
        params.dealFilePath.push(fileList.value[i].url)
      }
      params.dealFileName = params.dealFileName
        ? params.dealFileName.toString()
        : ''
      params.dealFilePath = params.dealFilePath
        ? params.dealFilePath.toString()
        : ''
      btnLoading.value = true
      let array = []
      try {
        const res = await getTaskDeal(params)
        // 修改任务处理状态
        if (props.rowId) {
          getTodoMessageHandle({ id: props.rowId }).then(res => {
            console.log('res==>', res)
          })
        }

        if (res.code === 200) {
          proxy.$modal.msgSuccess('操作成功')
          btnLoading.value = false
          array = res.data
          console.log('array', array, array !== undefined && array.length > 0)
          for (let i = 0; i < array.length; i++) {
            let mesVoData = {
              businessId: '结果反馈-通知-' + array[i].operateId, //业务ID
              content: `${props.dialogParam.titleName}:${params.remark}`,
              followDate: undefined, //跟进日期
              followType: undefined, //跟进方式
              impSign: props.dialogParam.impSign, //重要程度:0-非常重要，1-重要，2-一般
              receiver: array[i].belongId, //接收人id
              receiverName: array[i].belongName, //接收人中文
              reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
              sendTime: gettime.value, //发送时间
              sender: userStore.user.nickName, //发送人
              title: `您有一条'${props.dialogParam.titleName}'任务的结果反馈`, //待办标题
              type: 0, //待办类型:0-普通，1-流程
              serviceType: '10', //服务类型  0-项目，1-订单，2-客户，3-工单，4-任务，5-产品，6-合同，7-公告，8-日程，9-回款
              urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
              urlName: '前往处理', //待办链接名称(多链接名称用英文逗号隔开)
              url: `/rsgl/other/taskProcessing?id=${array[i].taskId}&operateId=${array[i].operateId}` //待办链接(多链接用英文逗号隔开)
            }
            console.log('mesVoData==>', mesVoData)
            // addManage(mesVoData)
          }
          router.push({
            path: '/rsgl/other/taskManage'
          })
          handleClose()
        }
      } catch (error) {
        btnLoading.value = false
      }
    }
  })
}
const emit = defineEmits(['close'])
// 取消
function handleClose() {
  dialogVisible.value = false
  btnLoading.value = false
  formParams.value = {}
  fileList.value = []
  emit('close')
}
</script>
<style lang="scss">
.dialogStyle {
  .el-dialog__header {
    @apply mr-0  text-#666 font-semibold bg-#f5f5f5;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
  }
  .footer {
    @apply text-right border-t border-t-solid border-gray-100 pt-20px mt-20px;
  }
}
</style>
